<template>
  <el-card class="login-card" shadow="hover" style="max-width: 450px; margin: 150px auto; background: #f8f9fa; border-radius: 8px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);">
    <template #header>
      <div class="card-header" style="display: flex; justify-content: center; font-size: 20px; color: #2c3e50;">
        <span>用户登录</span>
      </div>
    </template>
    <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px" class="login-form" status-icon>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入用户名" clearable prefix-icon="el-icon-user"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" clearable prefix-icon="el-icon-lock"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" class="login-btn" style="width: 100%; background: #2c3e50; border-color: #2c3e50;">登录</el-button>
      </el-form-item>
    </el-form>
    <div style="text-align: center; margin-top: 10px;"><el-link type="primary" @click="() => $router.push('/register')">没有账号？那去注册呗</el-link></div>
  </el-card>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../store/auth'

const loginFormRef = ref(null)
const router = useRouter()
const authStore = useAuthStore()
const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const submitForm = () => {
  if (!loginFormRef.value) return
  loginFormRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('登录成功')
      authStore.login(loginForm.username)
      router.push('/');
    } else {
      ElMessage.error('请检查输入信息')
      return false
    }
  })
}

const resetForm = () => {
  if (!loginFormRef.value) return
  loginFormRef.value.resetFields()
}
</script>

<style scoped>
.login-card {
  width: 450px;
  margin: 150px auto;
}
.card-header {
  font-size: 20px;
  color: #2c3e50;
}
.login-btn:hover {
  background: #34495e; 
  border-color: #34495e; 
}
</style>